﻿using MongoRepository;
using PushNotificationsHelper.Demo.DataContracts;
using PushNotificationsHelper.WindowsApp;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;

namespace PushNotificationsHelper.Demo
{
    public class DemoService : IDemoService
    {
        public void RegisterNotificationChannel(UserInfo userInfo)
        {
            MongoRepository<UserInfo> repository = new MongoRepository<UserInfo>();
            if (repository.FirstOrDefault(u => u.Id.Equals(userInfo.Id)) != null)
            {
                repository.Delete(userInfo.Id);
            }
            userInfo = repository.Add(userInfo);
        }

        public void ConfigureNotificationChannel(UserInfo userInfo)
        {
            MongoRepository<UserInfo> repository = new MongoRepository<UserInfo>();
            repository.Update(userInfo);
        }

        public void SendMessage(UserInfo sender, UserInfo receiver, string message)
        {
            MongoRepository<UserInfo> repository = new MongoRepository<UserInfo>();
            var user = repository.FirstOrDefault(u => u.Id.Equals(receiver.Id));
            if (user != null && user.NotificationConfiguration != null && user.NotificationConfiguration.NotificationChannel != null)
            {

                string key = ConfigurationManager.AppSettings["SecretKey"];
                string sid = ConfigurationManager.AppSettings["Sid"];
                ToastNotification.CreateToastNotification(key, sid)
                    .UsingTemplate(ToastTemplate.ToastText02)
                    .WithText(new List<string>
                       {
                           "Nuovo messaggio",
                           message
                       })
                    .SendPushNotification(repository.FirstOrDefault(u => u.Id.Equals(receiver.Id)).NotificationConfiguration.NotificationChannel);

                TileNotification.CreateTileNotification(key, sid)
                    .UsingTemplate(TileTemplate.TileSquare150x150Text01)
                    .WithText(new List<string>
                       {
                           sender.Id,
                           message
                       })
                    .SendPushNotification(repository.FirstOrDefault(u => u.Id.Equals(receiver.Id)).NotificationConfiguration.NotificationChannel);


            }
        }

        public void InviteToChat(UserInfo sender, UserInfo receiver)
        {
            throw new NotImplementedException();
        }

        public void RespondToAnInvitation(UserInfo guest, UserInfo inviteSender)
        {
            throw new NotImplementedException();
        }
    }
}
